import Event from "./Event";
export default class EventTarget{
    listeners: any = {}
    constructor(){}
    on(type:string, callback:Function) {
        let stack = this.listeners[type];
        if(!stack) {
            stack = [];
            this.listeners[type] = stack;
        }
        this.off(type, callback);
        stack.push(callback);
    }
    off(type:string, callback:Function){
        let stack = this.listeners[type];
        if(!stack) return;
        for (var i = 0, l = stack.length; i < l; i++) {
            if (stack[i] === callback){
                stack.splice(i, 1);
                return;
            }
        }
    }
    emit(event: Event|string, data?:any){
        let e:Event
        if(typeof event === 'string'){
            e = new Event()
            e.type = event
        }else{
            e = event
        }
        let stack = this.listeners[e.type]
        if (!stack) return true;
        e.currentTarget = this
        e.timeStamp = Date.now()
        e.data = data || null
        for (var i = 0, l = stack.length; i < l; i++) {
            if(stack[i]) stack[i].call(this, e);
        }
        return !e.defaultPrevented;
    }
}